﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Locker
{
    class Program
    {
        static long uniqueRes = 0; // 唯一资源
        // 锁对象
        static object locker = new object();


        static void DealRes()
        {
            // 将资源锁上
            lock (locker)
            {
                // 再来一次lock，会死锁吗？！
                lock (locker)
                {
                    for (int i = 0; i < 10000; i++)
                    {
                        uniqueRes += 1;
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello Thread Locker!");

            // 开启4个线程，模拟同时操作资源
            var thds = new List<Thread>();
            for (int i = 0; i < 4; i++)
            {
                var t = new Thread(DealRes);
                thds.Add(t);
                t.Start();
            }

            foreach (var t in thds)
            {
                t.Join();
            }
            Console.WriteLine($"sum: {uniqueRes}");
            Console.ReadKey();
        }
    }
}
